import com.microsoft.playwright.Browser;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.WaitUntilState;
import pojo.Item;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class BrowserDriverDownload {
    public static void main(String[] args) {
        long start=System.currentTimeMillis();
        // 创建Playwright实例
        Browser browser = null;
        List<String> magnetLink = null;
        // 调整导航等待策略，只等待网络空闲
        Page.NavigateOptions options = new Page.NavigateOptions().setWaitUntil(WaitUntilState.DOMCONTENTLOADED);
        try (Playwright playwright = Playwright.create()) {
            magnetLink = new ArrayList<>();
            // 设置请求头信息
            Map<String, String> headers = new HashMap<>();
            headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            // 启动Chromium浏览器
            browser = playwright.chromium().launch();
            // 打开一个新页面
            Page page = browser.newPage();
            page.setExtraHTTPHeaders(headers);
            // 导航到指定URL
            String url="https://taa.668552.xyz/list.php?class=guochan";
            System.out.println("正在访问："+url);
            // 拦截图片请求
            page.route("**/*.{png,jpg,jpeg,gif,svg,woff,woff2,ttf,mp4,webm}", route -> {
                // 阻止图片请求
                route.abort();
            });
            page.navigate(url,options);
// 定位到 ul.list 下的所有 a 标签
            Locator links = page.locator("div.post.post-last ul.list a");
            // 获取所有 a 标签的 href 属性值
            List<Item> hrefs = new ArrayList<>();
            // 获取定位到的元素数量
            int count = links.count();
            // 使用 for 循环遍历每个元素
            for (int i = 0; i < count; i++) {
                Item item=new Item();
                // 获取当前索引对应的元素
                Locator currentLink = links.nth(i);
                // 执行 JavaScript 代码获取绝对 href 属性
                String absoluteHref = currentLink.evaluate("(element) => element.href").toString();
                String textContent = currentLink.evaluate("(element) => element.text").toString();
                // 创建临时 <div> 元素并执行 document.write 代码，提取实际文本
//                String realText = page.evaluate("(code) => {" +
//                        "const tempDiv = document.createElement('div');" +
//                        "const originalWrite = document.write;" +
//                        "document.write = function(text) {" +
//                        "    tempDiv.innerHTML += text;" +
//                        "};" +
//                        "try {" +
//                        "    eval(code);" +
//                        "} catch (e) {}" +
//                        "document.write = originalWrite;" +
//                        "return tempDiv.textContent.trim();" +
//                        "}", textContent).toString();

                if (!textContent.isEmpty()) {
                    item.setTitile(textContent);
                }
                if (absoluteHref != null &&!absoluteHref.isEmpty()) {
                    // 如果绝对 href 属性存在，添加到结果列表中
                    item.setLocation(absoluteHref);
                }
                hrefs.add(item);
            }
            System.out.println("已经获取到了所有条目，共"+hrefs.size()+"条");
            hrefs = hrefs.stream()
                    .filter(s -> !s.getLocation().contains("ids"))
                    .collect(Collectors.toList());
            System.out.println("根据需求，过滤掉ids后，还剩余："+hrefs.size()+"条");
            // 遍历并打印所有 href 属性值
            int index=0;
            for (Item href : hrefs) {
                System.out.println("正在访问第"+(index++)+"条，地址为: " + href.getLocation());
                // 打开一个新页面
                Page page2 = browser.newPage();
                page2.setExtraHTTPHeaders(headers);
                // 拦截图片请求
                page2.route("**/*.{png,jpeg,gif,svg,woff,woff2,ttf,mp4,webm}", route -> {
                    // 阻止图片请求
                    route.abort();
                });
                page2.navigate(href.getLocation(),options);
                // 定义截图保存的绝对路径
// 找到 _ 的位置
                int underscoreIndex = href.getLocation().lastIndexOf("_");
                // 找到 . 的位置
                int dotIndex = href.getLocation().lastIndexOf(".");
                String result= String.valueOf(index);
                if (underscoreIndex != -1 && dotIndex != -1 && underscoreIndex < dotIndex) {
                    // 截取所需部分
                    result = href.getLocation().substring(underscoreIndex + 1, dotIndex);
                }
                String screenshotPath = "C:\\IdeaProject\\Playwright\\截屏\\"+result+".png";
                // 截取整个页面的屏幕截图，并保存到指定路径
//                page2.evaluate("window.scrollTo(0, 600)");
//                page2.screenshot(new Page.ScreenshotOptions().setPath(Paths.get(screenshotPath)));


                // 起始滚动位置
                int startScroll = 400;

                // 获取页面视口高度
                int viewportHeight = page2.viewportSize().height;

                // 滚动到起始位置
                page2.evaluate("window.scrollTo(0, " + startScroll + ")");

                // 获取页面的完整高度
                int pageHeight = (int) page2.evaluate("document.body.scrollHeight");

                BufferedImage combinedImage = null;
                Graphics2D g2d = null;
                int totalHeight = 0;

                for (int scrollPos = startScroll; scrollPos < pageHeight; scrollPos += viewportHeight) {
                    // 滚动页面
                    page2.evaluate("window.scrollTo(0, " + scrollPos + ")");
                    // 等待页面滚动稳定
                    page2.waitForTimeout(500);

                    // 截取当前部分的屏幕截图
                    String tempScreenshotPath = "temp_" + scrollPos + ".png";
                    page2.screenshot(new Page.ScreenshotOptions().setPath(Paths.get(tempScreenshotPath)));

                    // 读取当前截图
                    BufferedImage currentImage = ImageIO.read(new File(tempScreenshotPath));

                    if (combinedImage == null) {
                        // 初始化合并后的图像
                        combinedImage = new BufferedImage(currentImage.getWidth(), pageHeight - startScroll, BufferedImage.TYPE_INT_RGB);
                        g2d = combinedImage.createGraphics();
                    }

                    // 处理最后一次截图，避免超出页面底部
                    int heightToDraw = Math.min(viewportHeight, pageHeight - scrollPos);
                    BufferedImage croppedImage = currentImage.getSubimage(0, 0, currentImage.getWidth(), heightToDraw);

                    // 将当前截图绘制到合并后的图像上
                    g2d.drawImage(croppedImage, 0, totalHeight, null);
                    totalHeight += heightToDraw;

                    // 删除临时截图文件
                    new File(tempScreenshotPath).delete();
                }

                // 确保保存目录存在
                File outputFile = new File(screenshotPath);
                File parentDir = outputFile.getParentFile();
                if (parentDir != null && !parentDir.exists()) {
                    if (!parentDir.mkdirs()) {
                        System.err.println("无法创建保存目录: " + parentDir.getAbsolutePath());
                        return;
                    }
                }

                // 保存最终的长截图到指定路径
                try {
                    ImageIO.write(combinedImage, "png", outputFile);
                } catch (IOException e) {
                    System.err.println("保存长截图时出错: " + e.getMessage());
                }

                // 释放资源
                if (g2d != null) {
                    g2d.dispose();
                }


                String relativeDownloadLink = page2.getByText("下载链接").getAttribute("href");
                if (relativeDownloadLink != null) {
                    // 使用 JavaScript 计算绝对 URL
                    String absoluteDownloadLink = page2.evaluate("() => new URL('" + relativeDownloadLink + "', window.location.href).href").toString();
                    try {
                        Page page3 = browser.newPage();
                        page3.setExtraHTTPHeaders(headers);
                        // 拦截图片请求
                        page3.route("**/*.{png,jpg,jpeg,gif,svg,woff,woff2,ttf,mp4,webm,css}", route -> {
                            // 阻止图片请求
                            route.abort();
                        });
                        page3.navigate(absoluteDownloadLink,options);
//                        System.out.println("成功访问下载链接: " + absoluteDownloadLink);
                        String page3Href = page3.getByText("点击打开磁力链接").getAttribute("href");
//                        System.out.println("磁力链接地址：" + page3Href);
                        magnetLink.add(page3Href);
                    } catch (Exception e) {
                        System.err.println("访问下载链接 " + absoluteDownloadLink + " 失败。错误信息: " + e.getMessage());
                    }
                } else {
                    System.out.println("未找到有效的下载链接。");
                }
            }
            // 关闭浏览器
            browser.close();
        }catch (Exception e){
            System.out.println(e);
        } finally{
            // 记录程序结束时间
            long endTime = System.currentTimeMillis();
            System.out.println("任务结束，耗时"+(endTime-start)/1000+"秒");
            //打印链接地址
            if (magnetLink!=null&&magnetLink.size()!=0){
                System.out.println("下面打印磁力链接地址，共" + magnetLink.size() + "条磁力链接");
                magnetLink.stream().forEach(System.out::println);
            }
        }
    }
}
